'use strict';
const Sequelize = require('sequelize');
const Controller = require('egg').Controller;
class AddressController extends Controller {
  //添加地址
  /**
   * @api {Post} /api/address 添加地址
   * @apiGroup 地址
   * @apiParam {String}  authorization     ⚡登录成功后的token值
   * @apiParam {String}  name        ⚡用户名
   * @apiParam {String}  phone       ⚡手机号码
   * @apiParam {String}  area        ⚡地区id集合
   * @apiParam {String}  area_code   ⚡第三方组件地区id集合
   * @apiParam {String}  area_name   ⚡省份城市地区
   * @apiParam {String}  desc        ⚡详细地址
   * @apiParam {String}  post_code   邮政编码
   * @apiParamExample 参数模板
  {
      "authorization":"123456789abcdefqwerxyzbluejgoods"
      name: "jack",
      phone: 12345678912,
      area: "2,52,501",
      area_name: "北京省市辖区西城区",
      desc: "阿巴阿巴"
    }
   * @apiSuccessExample 成功返回
   * {
   *    "msg":'添加成功',
   *     "result": {
          "default_set": 0,         //0非默认地址，1默认地址
          "status": 1,              //地址状态1正常，2删除
          "id": 5,                  //地址id
          "name": "jack",           //用户名称
          "phone": "12345678912",   //手机号码
          "area": "2,52,501",       //地区id集合
          "desc": "阿巴阿巴",        //详细地址
          "user_id": 1,             //用户id
          "updatedAt": "2021-08-23T02:34:14.302Z",
          "createdAt": "2021-08-23T02:34:14.302Z"
        }
   * }
   *
   * @apiErrorExample 错误返回
   * {
   *  "msg":"添加失败"
   * }
   *
   */
  async create() {
    const { ctx } = this;
    const { Address } = this.app.model.Tables.Shop;
    const dataObj = ctx.request.body;

    try {
      if (
        new ctx.helper.checkData(this, 'name', 'phone', 'desc').checkDataRes
      ) {
        dataObj.user_id = ctx.userInfo.id;
        if (dataObj.default_set == 1) {
          const result = await Address.findAll({
            where: {
              user_id: ctx.userInfo.id,
            },
          });
          let j = 0;
          while (result[j]) {
            await result[j].update({
              default_set: '0',
            });
            j++;
          }
        }
        dataObj.area = dataObj.area || '2,52,500';
        dataObj.default_set = String(dataObj.default_set) || '0';
        const result = await Address.create(dataObj);
        ctx.body = result
          ? ctx.response.success(result, '添加成功')
          : ctx.response.error(result, '添加失败');
      }
    } catch (error) {
      ctx.body = ctx.response.error(error.message);
    }
  }

  // 根据地址ID获取地址信息
  async show() {
    const { ctx } = this;
    const { Address } = this.app.model.Tables.Shop;
    const { id } = ctx.params;

    try {
      // 根据ID获取地址信息
      const result = await Address.findByPk(id);
      ctx.body = ctx.response.success(result);
    } catch (err) {
      ctx.body = ctx.response.error(err.message);
    }
  }

  // 获取自己的地址列表
  /**
   * @api {Get} /api/address 获取自己的地址列表
   * @apiGroup 地址
   * @apiParam {String}  authorization ⚡登录成功后的token值
   * @apiParamExample 参数模板
  {
    "authorization":"123456789abcdefqwerxyzbluejgoods"
  }
   * @apiSuccessExample  成功返回
  {
      "msg": "成功操作",
      "result": [
      {
          "id": 3,                          //地址id
          "user_id": 1,                     //用户id
          "name": "测试2",                  //用户名称
          "phone": "12345678912",           //手机号码
          "area": "2,52,500",               //地区id集合
          "area_name": "北京省市辖区东城区",  //省市区
          "desc": "aaaa",                   //详细地址
          "post_code": "",                  //邮编
          "default_set": "0",               //0非默认地址，1默认地址
          "status": "1",                    //地址状态1正常，2删除
          "createdAt": "2021-08-16T07:14:51.000Z",
          "updatedAt": "2021-08-23T02:25:34.000Z"
      },
      {
          "id": 2,
          "user_id": 1,
          "name": "测试",
          "phone": "12345678912",
          "area": "5,62,605",
          "area_name": "甘肃省兰州区城关区",
          "desc": "aaaa",
          "post_code": "434400",
          "default_set": "0",
          "status": "1",
          "createdAt": "2021-08-16T07:14:32.000Z",
          "updatedAt": "2021-08-23T02:25:34.000Z"
      },
      {
          "id": 1,
          "user_id": 1,
          "name": "jack",
          "phone": "12345678912",
          "area": "11,151,1283",
          "area_name": "河南省开封区鼓楼区",
          "desc": "玛卡巴卡",
          "post_code": "434400",
          "default_set": "1",
          "status": "1",
          "createdAt": "2021-08-11T07:32:02.000Z",
          "updatedAt": "2021-08-23T02:25:34.000Z"
      }
    ]
  }
   * @apiErrorExample  错误返回
   * {
   *   "msg": "获取自己的地址列表失败"
   * }
   */
  async index() {
    const { ctx } = this;
    try {
      const Op = Sequelize.Op;
      const { Address } = this.app.model.Tables.Shop;
      const result = await Address.findAll({
        order: [['id', 'DESC']],
        where: {
          user_id: ctx.userInfo.id,
          status: {
            [Op.ne]: '2',
          },
        },
      });
      if (result) {
        ctx.body = ctx.response.success(result);
      } else {
        ctx.body = ctx.response.error('获取自己的地址列表失败');
      }
    } catch (error) {
      ctx.body = ctx.response.error(error.message);
    }
  }

  // 获取默认地址
  /**
   * @api {Get} /api/defalutAddress  获取默认地址
   * @apiGroup 地址
   * @apiParam {String}  authorization ⚡登录成功后的token值
   * @apiParamExample 参数模板
  {
    "authorization":"123456789abcdefqwerxyzbluejgoods",
  }
   * @apiSuccessExample  成功返回
  {
      "msg": "成功操作",
      "result": {
      "id": 1,                            //地址id
      "user_id": 1,                       //用户id
      "name": "jack",                     //用户名称
      "phone": "12345678912",             //手机号码
      "area": "11,151,1283",              //地区id集合
      "area_name": "河南省开封区鼓楼区"     //省市区
      "desc": "detail address",            //详细地址
      "post_code": "434400",               //邮编
      "default_set": "1",                  //0非默认地址，1默认地址
      "status": "1"                        //地址状态1正常，2删除
      }
  }
   * @apiErrorExample  错误返回
   * {
   *   "msg": "找不到该地址信息"
   * }
   */
  async defalutAddress() {
    const { ctx } = this;
    try {
      const Op = Sequelize.Op;
      const { Address } = this.app.model.Tables.Shop;

      const result = await Address.findOne({
        where: {
          user_id: ctx.userInfo.id,
          default_set: {
            [Op.or]: ['1', 1],
          },
          status: {
            [Op.ne]: '2',
          },
        },
      });
      if (result) {
        ctx.body = ctx.response.success(result);
      } else {
        // 找不到默认的，找当前user_id的第一个地址
        const result2 = await Address.findOne({
          where: {
            user_id: ctx.userInfo.id,
            status: {
              [Op.ne]: '2',
            },
          },
        });

        if (result2) {
          ctx.body = ctx.response.success(result2);
        } else {
          ctx.body = ctx.response.error('找不到该地址信息');
        }
      }
    } catch (error) {
      ctx.body = ctx.response.error(error.message);
    }
  }

  // 更新地址信息
  /**
     * @api {put} /api/address/:id 更新地址信息
     * @apiGroup 地址
     * @apiParam {String}  authorization     ⚡登录成功后的token值
     * @apiParam {String}  name        用户名    
     * @apiParam {String}  phone       手机号码  
     * @apiParam {String}  area        地区id集合
     * @apiParam {String}  area_code   第三方组件地区id集合
     * @apiParam {String}  desc        详细地址  
     * @apiParam {String}  post_code   邮政编码
     * @apiParam {String}  status      状态（默认1 正常， 2 软删除）
     * @apiParamExample 参数模板
    {
      "authorization":"123456789abcdefqwerxyzbluejgoods"
      "name":"jack",
      "phone":"15826597289",
      "area":"2,52,500",
      "desc":"阿巴阿巴阿巴",
      "post_code":"434400",
      "status":"2"
    }
     * @apiSuccessExample  成功返回
    {
        "msg": "成功操作",
        "result": {
        "id": 1,                        //地址id
        "user_id": 1,                   //用户id
        "name": "jack",                 //用户名称
        "phone": "15826597289",         //手机号码
        "area": "2,52,500",             //地区id集合
        "area_name": "北京省市辖区东城区",//省市区
        "desc": "阿巴阿巴阿巴",           //详细地址
        "post_code": "434400",          //邮编
        "default_set": "0",             //0非默认地址，1默认地址
        "status": "1",                  //地址状态1正常，2删除
        "createdAt": "2021-08-11T07:32:02.000Z",
        "updatedAt": "2021-08-16T07:31:54.000Z"
        }
    }
     * @apiErrorExample  错误返回
     * {
     *   "msg": "找不到该地址信息"
     * }
     */

  async update() {
    const { ctx } = this;
    const dataObj = ctx.request.body;
    dataObj.status && (dataObj.status = dataObj.status.toString());
    dataObj.area = dataObj.area || '2,52,500';

    if (new ctx.helper.checkData(this).checkDataRes) {
      const id = ctx.params.id;
      try {
        const { Address } = this.app.model.Tables.Shop;
        const resultUser = await Address.findByPk(id);
        if (resultUser && resultUser.dataValues) {
          const result = await resultUser.update(dataObj);
          ctx.body = ctx.response.success(result.dataValues);
        } else {
          ctx.body = ctx.response.error('找不到该地址信息');
        }
      } catch (error) {
        ctx.body = ctx.response.error(error.message);
      }
    }
  }

  // 设置为默认地址
  /**
     * @api {post} /api/setDefault/:id 设置为默认地址
     * @apiGroup 地址
     * @apiParam {String}  id       ⚡地址id
     * @apiParam {String}  authorization ⚡登录成功后的token值
     * @apiParamExample 参数模板
    {
      "authorization":"123456789abcdefqwerxyzbluejgoods"
    }
     * @apiSuccessExample  成功返回
     {
        "msg": "成功操作",
        "result": {
        "id": 1,                        //地址id
        "user_id": 1,                   //用户id
        "name": "jack",                 //用户名称
        "phone": "15826597289",         //手机号码
        "area": "2,52,500",             //地区id集合
        "area_name": "北京省市辖区东城区",//省市区
        "desc": "阿巴阿巴阿巴",           //详细地址
        "post_code": "434400",          //邮编
        "default_set": "0",             //0非默认地址，1默认地址
        "status": "1",                  //地址状态1正常，2删除
        "createdAt": "2021-08-11T07:32:02.000Z",
        "updatedAt": "2021-08-16T07:31:54.000Z"
        }
    }
     * @apiErrorExample  错误返回
     * {
     *   "msg": "找不到该地址信息"
     * }
     */

  async setDefault() {
    const { ctx } = this;
    const id = ctx.params.id;
    try {
      const { Address } = this.app.model.Tables.Shop;
      const resultUser = await Address.findByPk(id);

      if (resultUser && resultUser.dataValues) {
        // 查找全部地址设置为 0
        const resultAll = await Address.findAll({
          where: {
            user_id: ctx.userInfo.id,
          },
        });
        let j = 0;
        while (resultAll[j]) {
          await resultAll[j].update({
            default_set: 0,
          });
          j++;
        }
        // 设置改地址为默认地址
        const result = await resultUser.update({
          default_set: 1,
          user_id: ctx.userInfo.id,
        });
        ctx.body = ctx.response.success(result.dataValues);
      } else {
        ctx.body = ctx.response.error('找不到该地址信息');
      }
    } catch (error) {
      ctx.body = ctx.response.error(error.message);
    }
  }

  /**
     * @api {delete} /api/address/:id 删除地址
     * @apiGroup 地址
     * @apiParam {String}  authorization ⚡登录成功后的token值
     * @apiParam {String}  id        ⚡地址id
     * @apiParamExample 参数模板
    {
      "authorization":"123456789abcdefqwerxyzbluejgoods"
    }
     * @apiSuccessExample 成功返回
     * {
     *    "msg":'删除成功'
     * }
     *
     * @apiErrorExample 错误返回
     * {
     *  "msg":"删除失败"
     * }
     *
     */

  async destroy() {
    const { ctx } = this;
    const dataObj = { status: 2 };

    const id = ctx.params.id;
    try {
      const { Address } = this.app.model.Tables.Shop;
      const resultUser = await Address.findByPk(id);
      if (resultUser && resultUser.dataValues) {
        await resultUser.update(dataObj);
        ctx.body = ctx.response.success('删除成功');
      } else {
        ctx.body = ctx.response.error('已删除');
      }
    } catch (error) {
      ctx.body = ctx.response.error(error.message);
    }
  }
}

module.exports = AddressController;
